package com.springboot.jdk.concurrency;

import java.util.concurrent.CountDownLatch;

/**
 * @author: zr
 * @date: 2021-10-07
 */
public class CountDownLatchDemo {

    public static void main(String[] args) throws InterruptedException {
        // 我希望有多少个线程执行CountDownLatch 操作=====
        CountDownLatch countDownLatch = new CountDownLatch(2);

        new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);

                    System.out.println("线程1开始执行，休眠1秒");
                    Thread.sleep(1000);

                    System.out.println("线程1准备执行 countDown 操作");
                    countDownLatch.countDown();
                    System.out.println("线程1完成 countDown 操作");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    System.out.println("线程2开始执行，休眠1秒");
                    Thread.sleep(1000);

                    System.out.println("线程2准备执行 countDown 操作");
                    countDownLatch.countDown();
                    System.out.println("线程2完成 countDown 操作");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        System.out.println("main线程准备执行 CountDownLatch 的 await 操作，将会同步阻塞等待。。。");
        // 所有的任务都干完了，才会继续往下执行， 同步阻塞等待
        // 此时有多个线程阻塞到这里，都阻塞 await() 方法这里了
        // 假设 此时 countDownLatch之后，state == 0， 此时会字节触发 等待队列里所有线程全部唤醒，继续往下执行
        countDownLatch.await();
        System.out.println("所有线程完成 countDown 操作，main线程的await阻塞等待借宿");
    }
}
